package com.xwamp.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式公共类
 * 
 * @author SoChishun
 * @version 1.0 2017-5-18
 */
public class RegexUtil {
	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		return isNumeric(str, 0);
	}

	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str
	 * @param prefixType
	 *            1:前缀是-符号;2:前缀是+/-符号;3:无前缀数字
	 * @return
	 */
	public static boolean isNumeric(String str, Integer prefixType) {
		if (null == str) {
			return false;
		}
		if (null == prefixType) {
			prefixType = 0;
		}
		String strpattern;
		switch (prefixType) {
		case 1:
			strpattern = "^-?\\d+";
			break;
		case 2:
			strpattern = "^[-\\+]?[0-9]+(\\.[0-9]+)?$";
			break;
		default:
			strpattern = "\\d*";
			break;
		}
		return isMatch(str, strpattern);
	}

	public static boolean isMatch(String str, String strpattern) {
		if (null == str || null == strpattern) {
			return false;
		}
		Pattern pattern = Pattern.compile(strpattern);
		Matcher matcher = pattern.matcher(str);
		boolean result = matcher.matches();
		return result;
	}

	/**
	 * 匹配手机号码
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isMobile(String str) {
		// 更严格：^1[3|4|5|8][0-9]\d{8}$
		return isMatch(str, "^1\\d{10}$");
	}

	public static boolean isEmail(String str) {
		return isMatch(str, "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	}

	/**
	 * 匹配18位身份证号码
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isIdCardNumber(String str) {
		return isMatch(str, "^(\\d{6})(18|19|20)?(\\d{2})([01]\\d)([0123]\\d)(\\d{3})(\\d|X|x)?$");
	}

	public static boolean isUserName(String str) {
		return isMatch(str, "^[a-zA-Z][a-zA-Z0-9_]{4,15}$");
	}

	public static boolean isPassword(String str) {
		return isMatch(str, "^[a-zA-Z]\\w{5,17}$");
	}
}
